package com.tancire.net.service.impl;

import java.util.List;
import javax.annotation.Resource;

import cn.hutool.core.util.IdUtil;
import com.tancire.common.core.redis.RedisCache;
import com.tancire.common.utils.DateUtils;
import org.springframework.stereotype.Service;
import com.tancire.net.mapper.ShopGoodsMapper;
import com.tancire.net.domain.ShopGoods;
import com.tancire.net.service.IShopGoodsService;

import static com.tancire.common.constant.Constants.GOODS_STOCK_PREFIX;

/**
 * 商品管理Service业务层处理
 *
 * @author chenchao
 * @date 2023-11-20
 */
@Service
public class ShopGoodsServiceImpl implements IShopGoodsService {

    @Resource
    private ShopGoodsMapper shopGoodsMapper;

    @Resource
    private RedisCache redisCache;

    /**
     * 查询商品管理
     *
     * @param id 商品管理主键
     * @return 商品管理
     */
    @Override
    public ShopGoods selectShopGoodsById(Long id) {
        return shopGoodsMapper.selectShopGoodsById(id);
    }

    /**
     * 查询商品管理列表
     *
     * @param shopGoods 商品管理
     * @return 商品管理
     */
    @Override
    public List<ShopGoods> selectShopGoodsList(ShopGoods shopGoods) {
        return shopGoodsMapper.selectShopGoodsList(shopGoods);
    }

    /**
     * 新增商品管理
     *
     * @param shopGoods 商品管理
     * @return 结果
     */
    @Override
    public int insertShopGoods(ShopGoods shopGoods) {
        shopGoods.setCreateTime(DateUtils.getNowDate());
        shopGoods.setId(IdUtil.getSnowflakeNextId());
        int count = shopGoodsMapper.insertShopGoods(shopGoods);
        this.refreshGoodsStock(shopGoods);
        return count;
    }

    /**
     * 刷新redis库存
     *
     * @param shopGoods
     */
    private void refreshGoodsStock(ShopGoods shopGoods) {
        // 缓存数量
        redisCache.setCacheObject(GOODS_STOCK_PREFIX + shopGoods.getId(), String.valueOf(shopGoods.getGoodsTotal()));
    }

    /**
     * 修改商品管理
     *
     * @param shopGoods 商品管理
     * @return 结果
     */
    @Override
    public int updateShopGoods(ShopGoods shopGoods) {
        shopGoods.setUpdateTime(DateUtils.getNowDate());
        this.refreshGoodsStock(shopGoods);
        return shopGoodsMapper.updateShopGoods(shopGoods);
    }

    /**
     * 批量删除商品管理
     *
     * @param ids 需要删除的商品管理主键
     * @return 结果
     */
    @Override
    public int deleteShopGoodsByIds(Long[] ids) {
        return shopGoodsMapper.deleteShopGoodsByIds(ids);
    }

    /**
     * 删除商品管理信息
     *
     * @param id 商品管理主键
     * @return 结果
     */
    @Override
    public int deleteShopGoodsById(Long id) {
        return shopGoodsMapper.deleteShopGoodsById(id);
    }

    /**
     * 更新商品数量
     *
     * @param id
     * @param count
     */
    @Override
    public void updateGoodsStock(Long id, int count) {
        this.shopGoodsMapper.updateGoodsStock(id, count);
    }
}
